<?

function errRedirect($errorType, $errorMsg, $pageName, $errLine) {
    //eg errRedirect(2,"Invalid Access",$_SERVER['PHP_SELF'],0);
    $errorMsg = urlencode($errorMsg);
    $pageName = urlencode($pageName);
    echo "<script>window.location='os_error_page.php?pagename=$pageName&errmsg=$errorMsg&errtype=$errorType&errline=$errLine'</script>";
}

function truncate($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
    if ($considerHtml) {
        // if the plain text is shorter than the maximum length, return the whole text
        if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
            return $text;
        }
        // splits all html-tags to scanable lines
        preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
        $total_length = strlen($ending);
        $open_tags = array();
        $truncate = '';
        foreach ($lines as $line_matchings) {
            // if there is any html-tag in this line, handle it and add it (uncounted) to the output
            if (!empty($line_matchings[1])) {
                // if it's an "empty element" with or without xhtml-conform closing slash
                if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                    // do nothing
                    // if tag is a closing tag
                } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
                    // delete tag from $open_tags list
                    $pos = array_search($tag_matchings[1], $open_tags);
                    if ($pos !== false) {
                        unset($open_tags[$pos]);
                    }
                    // if tag is an opening tag
                } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                    // add tag to the beginning of $open_tags list
                    array_unshift($open_tags, strtolower($tag_matchings[1]));
                }
                // add html-tag to $truncate'd text
                $truncate .= $line_matchings[1];
            }
            // calculate the length of the plain text part of the line; handle entities as one character
            $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
            if ($total_length + $content_length > $length) {
                // the number of characters which are left
                $left = $length - $total_length;
                $entities_length = 0;
                // search for html entities
                if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                    // calculate the real length of all entities in the legal range
                    foreach ($entities[0] as $entity) {
                        if ($entity[1] + 1 - $entities_length <= $left) {
                            $left--;
                            $entities_length += strlen($entity[0]);
                        } else {
                            // no more characters left
                            break;
                        }
                    }
                }
                $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
                // maximum lenght is reached, so get off the loop
                break;
            } else {
                $truncate .= $line_matchings[2];
                $total_length += $content_length;
            }
            // if the maximum length is reached, get off the loop
            if ($total_length >= $length) {
                break;
            }
        }
    } else {
        if (strlen($text) <= $length) {
            return $text;
        } else {
            $truncate = substr($text, 0, $length - strlen($ending));
        }
    }
    // if the words shouldn't be cut in the middle...
    if (!$exact) {
        // ...search the last occurance of a space...
        $spacepos = strrpos($truncate, ' ');
        if (isset($spacepos)) {
            // ...and cut the text in this position
            $truncate = substr($truncate, 0, $spacepos);
        }
    }
    // add the defined ending to the text
    $truncate .= $ending;
    if ($considerHtml) {
        // close all unclosed html-tags
        foreach ($open_tags as $tag) {
            $truncate .= '</' . $tag . '>';
        }
    }
    return $truncate;
}

function getShippingDesc($shipping_id, $country_id, $state_id) {

    if ($country_id == "" || $state_id == "" || $shipping_id == "") {
        $return = "Please select your state and prefered shipping service for shipping info";
    } else {

        if ($shipping_id == 0) {
            $return = "<div class='dw_success'>Collect from store, no shipping charge</div>";
        } else {

            $shipping_cost = getShippingCost($shipping_id, $country_id, $state_id);
            
            if($shipping_cost=="-2"){
                $return = "<div class='dw_failed'>Shipping zone not found, please contact admin</div>";
            }elseif($shipping_cost=="-1"){
                $return = "<div class='dw_failed'>Total weight exceeded the limit, please contact admin</div>";
            }else{
            $return = "<div class='dw_success'>Your shipping fee for this order will be  " . $_SESSION['currency_code'] . " " . number_format($shipping_cost, 2) . "</div>";
            }
        }
    }

    return $return;
}

function getShippingCost($shipping_id, $country_id, $state_id) {
    if ($shipping_id == 0) {
        $shipping_cost = 0;
    } else {
        $total_weight = getTotalWeight();

        $get_max_weight = mysql_query("select a.id,a.weight,a.price,a.zone_id,b.country_id,b.zone_id from os_shipping_zone_rate a inner join os_shipping_zone_country b on a.zone_id=b.zone_id 
                                       where b.courier_id='$shipping_id' and b.country_id='$country_id' order by a.weight desc limit 1") or die(mysql_error());

        if (mysql_num_rows($get_max_weight) > 0) {
            $max_weight = mysql_result($get_max_weight, 0, "weight");
        } else {
            $max_weight = 0;
        }

        if ($total_weight > $max_weight) {
            $shipping_cost = -1; //over max weight
        } else {
            $get_cost = mysql_query("select a.id,a.weight,a.price,a.zone_id,b.country_id,b.zone_id from os_shipping_zone_rate a inner join os_shipping_zone_country b on a.zone_id=b.zone_id 
                                       where b.courier_id='$shipping_id' and b.country_id='$country_id' and a.weight>=$total_weight order by a.weight asc limit 1") or die(mysql_error());

            if (mysql_num_rows($get_cost) > 0) {
                $shipping_cost = mysql_result($get_cost, 0, "price");
            } else {
                $shipping_cost = -2; //no record found for courier under the selected zone
            }
        }
    }

    return $shipping_cost;
}

function getTotalWeight() {

    $total_weight = 0;
    foreach ($_SESSION['cart'] as $cartItems) {
        $itemId = $cartItems['id'];
        $quantity = $cartItems['quantity'];
        $addon_ids = $cartItems['addon_id'];

        $get_items = mysql_query("select * from os_product_inventory where id=" . $itemId);
        $item = mysql_fetch_array($get_items, MYSQL_ASSOC);
        $proId = $item['pid'];

        $get_product = mysql_query("select * from os_products where id=$proId");
        $a = mysql_fetch_array($get_product, MYSQL_ASSOC);
        $total_weight+=$a['product_weight'] * $quantity;

        if (is_array($addon_ids)) {
            for ($addon = 0; $addon < count($addon_ids); $addon++) {
                $addon_id = $addon_ids[$addon];
                $get_addon = mysql_query("select * from os_products where id='" . $addon_id . "'");
                $ap = mysql_fetch_array($get_addon, MYSQL_ASSOC);
                $total_weight+=$ap['product_weight'] * $quantity;
            }
        }
    }
    return $total_weight;
}

function getPaging($totalPerPage, $totalRecord, $currentPage, $pageUrl) {


    $totalpage = $totalRecord / $totalPerPage;

    if ($totalRecord % $totalPerPage > 0) {
        if (round($totalpage) > $totalpage) {
            $totalpage = round($totalpage);
        } else {
            $totalpage = round($totalpage + 1);
        }
    } else {
        $totalpage = round($totalpage);
    }


    $nextpage = $currentPage + 1;
    $prepage = $currentPage - 1;

    $output = "<table  cellpadding='0' cellspacing='0' >								
				<td height='45' >
					
					<a href='" . $pageUrl . "&page=" . $prepage . "'><img src='images/icons/paging_pre.png' border=0></a>
				</td>
				<td>
					<table>";

    if ($totalpage > 10) {

        $frompage = $currentPage - 2;


        if ($frompage <= 0 || $currentPage == 1 || $currentPage == 2) {
            $frompage = 1;
            $endpage = 10;
        } else {

            $endpage = $currentPage + 7;

            if ($endpage > $totalpage) {
                $endpage = $totalpage;
            }

            $testpage = 0;

            if ($currentPage > 2) {
                for ($paging = $frompage; $paging <= $endpage; $paging++) {

                    $testpage++;
                }

                if ($testpage < 10) {
                    $additionalpage = 10 - $testpage;

                    $frompage = $frompage - $additionalpage;
                }
            }
        }
    } else {
        $frompage = 1;
        $endpage = $totalpage;
    }

    for ($paging = $frompage; $paging <= $endpage; $paging++) {

        if ($paging == $currentPage) {
            $output.="<td align=center width='20px' class='paging_highlighted'>" . $paging . "</td>";
        } else {
            $output.="<td align=center width='20px' class='paging_outlighted'>
			<a href='" . $pageUrl . "&page=" . $paging . "' style='text-decoration:none'><font class='paging_outlighted'>" . $paging . "</font></a></td>";
        }
    }

    $output.="</table></td><td>";

    if ($currentPage == $totalpage) {

        $output.="<img src='images/icons/paging_next.png' border=0>";
    } else {

        $output.=" <a href='" . $pageUrl . "&page=" . $nextpage . "'><img src='images/icons/paging_next.png' border=0></a>";
    }

    $output.=" </td></table>";

    return $output;
}

function leading_zeros($value, $places) {
    $leading = "";
    if (is_numeric($value)) {
        for ($x = 1; $x <= $places; $x++) {
            $ceiling = pow(10, $x);
            if ($value < $ceiling) {
                $zeros = $places - $x;
                for ($y = 1; $y <= $zeros; $y++) {
                    $leading .= "0";
                }
                $x = $places + 1;
            }
        }
        $output = $leading . $value;
    } else {
        $output = $value;
    }
    return $output;
}

function getMemberPoints($member_id) {
    $get_bill = mysql_query("select * from os_bill_details where uid=$member_id and status>=6") or die(mysql_error());

    $points = 0;
    $redeemed = 0;
    if (mysql_num_rows($get_bill) > 0) {
        while ($c = mysql_fetch_array($get_bill)) {
            $total_amount = $c['transport_fees'] + $c['total_amount'];
            $discount = ($c['discount'] / 100) * $total_amount;
            $points = $total_amount - $discount;

            $get_voucher = mysql_query("select * from os_discount_voucher_used where bill_id=" . $c['id']) or die(mysql_error());
            if (mysql_num_rows($get_voucher) > 0) {
                $voucher = mysql_query("select * from os_discount_voucher where id='" . mysql_result($get_voucher, 0, "voucher_id") . "'") or die(mysql_error());
                $v = mysql_fetch_array($voucher, MYSQL_ASSOC);

                if ($v['discount_type'] == "P") {
                    $discount = ($total_allprice * $v['discount_amount']) / 100;
                    $points = $final_amount - $discount;
                } else {
                    $discount = $v['discount_amount'];
                    $points = $final_amount - $v['discount_amount'];
                }
            }
        }
    }

    $get_redeemed = mysql_query("select * from os_redeem_record where member_id=$member_id") or die(mysql_error());
    if (mysql_num_rows($get_redeemed) > 0) {
        while ($r = mysql_fetch_array($get_redeemed, MYSQL_ASSOC)) {
            $redeemed = $redeemed + $r['total_redeemed'];
        }
    }

    $points = $points - $redeemed;

    return $points;
}

function delete_line($find, $file) {
    $contents = array();
    $new_contents = "";
    $find = trim($find);
    $return = false;

    if (file_exists($file)) {
        if (is_writable($file)) {
            // open the file as an array, each line as an element
            if ($contents = file($file)) {
                // remove extra whitespace from each line
                $contents = array_map("trim", $contents);

                // loop through each line and see if it's the one we want<br />
                foreach ($contents as $line_number => $line) {
                    $lowercase_line = strtolower($line);
                    $lowercase_find = strtolower($find);
                    if ($lowercase_line == $lowercase_find) {
                        // this is where we remove the line
                        unset($contents[$line_number]);
                        $return = true;
                    }
                }

                // put the lines back together with a \n between each
                $new_contents = implode("\n", $contents);

                // open the file and delete its old contents
                if (!$handle = fopen($file, 'w')) {
                    trigger_error("$file could not be opened for writing", E_USER_NOTICE);
                    return false;
                } else {

                    if (fwrite($handle, $new_contents) !== false) {
                        // it worked
                        return $return;
                    }
                }
            } else {
                trigger_error("$file is not readable", E_USER_NOTICE);
                return false;
            }
        } else {
            trigger_error("$file is not writable", E_USER_NOTICE);
            return false;
        }
    } else {
        trigger_error("$file does not exist", E_USER_NOTICE);
        return false;
    }
}

function getDataById($table, $field, $byfield, $id) {
    $get = mysql_query("select $field from $table where $byfield='$id'") or die(mysql_error());
    if (mysql_num_rows($get) > 0) {
        $return = mysql_result($get, 0, $field);
    } else {
        $return = "unknown";
    }
    return $return;
}

function getProductUrl($id, $clean_url, $module_url_rewrite) {
    if ($module_url_rewrite == 0) {
        $product_url = "os_view_full.php?id=" . $id;
    } else {
        if ($clean_url == "") {
            $product_url = "os_view_full.php?id=" . $id;
        } else {
            $product_url = $clean_url . ".htm";
        }
    }

    return $product_url;
}

function getProductUrlAnchor($id) {

    $get_cat = mysql_query("select a.id, a.sub_cat_id, b.id as bid, b.clean_url from os_products a inner join os_sub_category b on a.sub_cat_id=b.id where a.id=$id") or die(mysql_error());


    $product_url = "os_view_product.php?cat=" . mysql_result($get_cat, 0, "clean_url") . "#jumpToProduct" . $id;

    return $product_url;
}

function productAvatar($get_product) {
    $module_promotion = $_SESSION['module_promotion'];
    $module_url_rewrite = $_SESSION['module_url_rewrite'];
    $no = 0;
    $tr1 = "";
    $tr2 = "";

    while ($a = mysql_fetch_array($get_product)) {
        if ($no % 3 == 0) {
            $tr1 = "<tr>";
            $tr2 = "</tr>";
        } else {
            $tr1 = "";
            $tr2 = "";
        }

        $get_pic = mysql_query("select * from os_productpic where product_id=" . $a['id'] . " order by order_id asc limit 1");

        if (mysql_num_rows($get_pic) == 0) {
            $pic = "empty";
            $piclink = "noimage.jpg";
            $fix = "";
        } else {
            $pic = mysql_fetch_array($get_pic, MYSQL_ASSOC);

            $piclink = $pic['name'];

            if ($pic["width"] - $pic["height"] > 0) {
                $fix = "width=180";
            } else {
                $fix = "height=130";
            }
        }

        $get_cat = mysql_query("select * from os_category where id=" . $a['cat_id']);
        $get_sub_cat = mysql_query("select * from os_sub_category where id=" . $a['sub_cat_id']);
        $product_url = getProductUrl($a['id'], $a['clean_url'], $module_url_rewrite);
        $image_link = ROOT_PATH . "productpic/thumbnails/" . $piclink;

        echo $tr1;
        echo "
		<td width='250' height='100%'  valign='top' >
			<table width='100%' height='100%' cellpadding='5'  >
				
				<tr>
					<td width='100%' align='center' valign='top' height='150'>
					
					<a href='" . $product_url . "'>
					<img src='required/thumbnail_resize.php?width=150&height=150&cropratio=1:1&image=" . $image_link . "' class='product_thumbnail_frame'/>
					</a>
					</td>
				</tr>
				<tr>
				<td align='center' valign='bottom'>";
        echo "</td></tr>			
				
				<tr>
				<td align='center' valign='bottom'>
				<strong><font class='product_title_small'>" . $a['display_name'] . "</font></strong><br>
				";


        echo "<br>
				
				<a href='$product_url' ><img src='images/buttons/view_details.png' border='0'></a>
				
				
					</td>
				</tr>
				<tr>
					<Td></td>
				</tr>
			</table>
			
		</td>";


        $no++;
    }

    echo $tr2;
}

function productList($get_product) {
    $module_promotion = $_SESSION['module_promotion'];
    $module_url_rewrite = $_SESSION['module_url_rewrite'];
    $no = 0;

    while ($a = mysql_fetch_array($get_product)) {
        if ($no % 3 == 0) {
            $tr1 = "<tr>";
            $tr2 = "</tr>";
        } else {
            $tr1 = "";
            $tr2 = "";
        }

        $get_pic = mysql_query("select * from os_productpic where product_id=" . $a['id'] . " order by order_id asc limit 1");

        if (mysql_num_rows($get_pic) == 0) {
            $pic = "empty";
            $piclink = "noimage.jpg";
            $fix = "";
        } else {
            $pic = mysql_fetch_array($get_pic, MYSQL_ASSOC);

            $piclink = $pic['name'];

            if ($pic["width"] - $pic["height"] > 0) {
                $fix = "width=200";
            } else {
                $fix = "height=150";
            }
        }

        $get_cat = mysql_query("select * from os_category where id=" . $a['cat_id']);
        $get_sub_cat = mysql_query("select * from os_sub_category where id=" . $a['sub_cat_id']);
        $product_url = getProductUrl($a['id'], $a['clean_url'], $module_url_rewrite);

        echo $tr1;
        echo "
		<td width='300' height='100%'  valign='top' >
			<table width='100%' height='100%' cellpadding='5' >
				
				<tr>
					<td width='100%' align='center' valign='top' height='150'>
					
					<a href='" . $product_url . "'><img  border=0 src='productpic/thumbnails/" . $piclink . "' $fix></a>
					</td>
				</tr>
				<tr>
				<td align='center' valign='bottom'>";
        echo "</td></tr>			
				
				<tr>
				<td align='center' valign='bottom'>
				<strong>" . $a['display_name'] . "</strong><br>
				";

        echo "<br><br>
					</td>
				</tr>
				
			</table>
			
		</td>";


        $no++;
    }

    echo $tr2;
}

function latestProductList($get_product) {
    $module_promotion = $_SESSION['module_promotion'];
    $module_url_rewrite = $_SESSION['module_url_rewrite'];
    $no = 0;

    while ($a = mysql_fetch_array($get_product)) {
        if ($no % 5 == 0) {
            $tr1 = "<tr>";
            $tr2 = "</tr>";
        } else {
            $tr1 = "";
            $tr2 = "";
        }

        $get_pic = mysql_query("select * from os_productpic where product_id=" . $a['id'] . " order by order_id asc limit 1");

        if (mysql_num_rows($get_pic) == 0) {
            $pic = "empty";
            $piclink = "noimage.jpg";
            $fix = "";
        } else {
            $pic = mysql_fetch_array($get_pic, MYSQL_ASSOC);

            $piclink = $pic['name'];

            if ($pic["width"] - $pic["height"] > 0) {
                $fix = "width=120";
            } else {
                $fix = "height=100";
            }
        }

        $get_cat = mysql_query("select * from os_category where id=" . $a['cat_id']);
        $get_sub_cat = mysql_query("select * from os_sub_category where id=" . $a['sub_cat_id']);
        $product_url = getProductUrl($a['id'], $a['clean_url'], $module_url_rewrite);
        $image_link = ROOT_PATH . "productpic/thumbnails/" . $piclink;


        echo "
		<td width='150' height='100'  valign='top'>
			<table width='100%' height='100%' cellpadding='5' >
				
				<tr>
					<td width='40%' align='center' valign='top' height='150' rowspan='2'>
					
					<a href='" . $product_url . "'>
					<img src='required/thumbnail_resize.php?width=120&height=120&cropratio=1:1&image=" . $image_link . "' class='product_thumbnail_frame' />
					</a>
					<br>
					<font class='product_title_small'>" . truncate($a['display_name'], 30) . "</font><br><br>
					";



        echo "<a href='" . $product_url . "'><img src='images/buttons/view_details.png' border='0'></a><br>
					
					</td>
				</tr>
				
			
			</table>
			
		</td>";


        $no++;
    }
}

function productAvatarRedeem($get_product) {

    $no = 0;
    $tr1 = "";
    $tr2 = "";
    while ($a = mysql_fetch_array($get_product)) {
        if ($no % 3 == 0) {
            $tr1 = "<tr>";
            $tr2 = "</tr>";
        } else {
            $tr1 = "";
            $tr2 = "";
        }

        $get_pic = mysql_query("select * from os_productpic where product_id=" . $a['id'] . " order by order_id asc limit 1");

        if (mysql_num_rows($get_pic) == 0) {
            $pic = "empty";
            $piclink = "noimage.jpg";
            $fix = "";
        } else {
            $pic = mysql_fetch_array($get_pic, MYSQL_ASSOC);

            $piclink = $pic['name'];

            if ($pic["width"] - $pic["height"] > 0) {
                $fix = "width=155";
            } else {
                $fix = "height=130";
            }
        }

        $get_cat = mysql_query("select * from os_category where id=" . $a['cat_id']);
        $get_sub_cat = mysql_query("select * from os_sub_category where id=" . $a['sub_cat_id']);


        echo $tr1;
        echo "
		<td width='300' height='100%'  valign='top'>
			<table width='100%' height='100%' cellpadding='5' class='solidborder'>
				<td align='center' height='45' valign='top'><strong>" . $a['product_name_eng'] . "</strong></td>
				<tr>
					<td width='100%' align='center' valign='top' height='150'>
					
					<a href='os_view_full.php?id=" . $a['id'] . "&type=redeem'><img  border=0 src='productpic/thumbnails/" . $piclink . "'></a>
					</td>
				</tr>
				<tr>
				<td align='center' valign='bottom'>";




        echo "</td></tr>			
				<tr><td align='center' valign='bottom'>";
        echo "Points Required : " . $a['points_required'] . "";

        echo "<br><input type='image' src='images/button_details.png' onClick='window.open(\"os_view_full.php?id=" . $a['id'] . "&type=redeem\",\"_self\")'>
					</td>
				</tr>
			</table>
			
		</td>";


        $no++;
    }

    echo $tr2;
}

function scoreBar($score) {
    switch ($score) {
        case 5:
            $statusdesc = "Very good";
            break;
        case 4:
            $statusdesc = "Not bad";
            break;
        case 3:
            $statusdesc = "Normal";
            break;
        case 2:
            $statusdesc = "Not good";
            break;
        case 1:
            $statusdesc = "Very poor";
            break;
    }
    return $statusdesc;
}

function convertMemberType($value) {
    if ($value == "N") {
        $return = "Normal User";
    } elseif ($value == "M") {
        $return = "Member";
    } else {
        $return = "Both Normal and VIP Member";
    }

    return $return;
}

function postageCount($area, $total_items) {

    if ($area == 0) {
        $total_price = "0";
    } else {
        $get_place = mysql_query("select * from os_postage_setting where area_id=$area and $total_items>=from_items and $total_items<=to_items") or die(mysql_error());

        if (mysql_num_rows($get_place) == 0) {
            $total_price = "0";
        } else {
            $total_price = number_format($_SESSION['currency_rate'] * mysql_result($get_place, 0, "total_price"), 2);
        }
    }
    return $total_price;
}

function redeemstatus_eng($statusid) {
    switch ($statusid) {

        case 0:
            $statusdesc = "Pending";
            break;
        case 1:
            $statusdesc = "Confirmed";
            break;
        case 2:
            $statusdesc = "Sent";
            break;
        case 3:
            $statusdesc = "Received";
            break;
        default:
            $statusdesc = "Unknown Status";
    }

    return $statusdesc;
}

function billstatus_eng($statusid) {
    switch ($statusid) {
        case -1:
            $statusdesc = "Order already expired";
            break;
        case -2:
            $statusdesc = "Buyer cancelled order";
            break;
        case -3:
            $statusdesc = "Buyer choose to pay by PayPal";
            break;
        case -4:
            $statusdesc = "Buyer paid by Paypal";
            break;
        case 1:
            $statusdesc = "Order under verifying";
            break;
        case 2:
            $statusdesc = "Order verified";
            break;
        case 3:
            $statusdesc = "Buyer made payment, awaiting payment verification";
            break;
        case 4:
            $statusdesc = "Payment received, goods to be delivered";
            break;
        case 5:
            $statusdesc = "Goods delivered";
            break;
        case 6:
            $statusdesc = "Goods received";
            break;
        case 7:
            $statusdesc = "Insufficient stock";
            break;
        case 8:
            $statusdesc = "Merchant cancelled order";
            break;
        case 9:
            $statusdesc = "Sales Closed";
            break;
        case 10:
            $statusdesc = "Buyer paid with credit card, goods to be delivered";
            break;
        default:
            $statusdesc = "Buyer didn't confirm payment method";
    }

    return $statusdesc;
}

function updateInventory($item_id, $amount, $adddeduct, $bid, $pid) {

    if ($adddeduct == "Add") {

        $update = mysql_query("update os_product_inventory set quantity=quantity+$amount where id=$item_id") or die(mysql_error());
        $system_remark = $amount . " item(s) returned from cancelled order";
        $user_remark = "[System Generated]invoice # $bid ";
        $insert = mysql_query("insert into os_stockrecord(pid,user_remarks,system_remarks,add_datetime,bid)values($pid,'$user_remark','$system_remark',now(),0)") or die(mysql_error());
    } else {
        $update = mysql_query("update os_product_inventory set quantity=quantity-$amount where id=$item_id") or die(mysql_error());
        $get_bill = mysql_query("select * from os_bill_details where id=" . $bid);
        $invoice_no = mysql_result($get_bill, 0, "invoice_number");
        $system_remark = $amount . " item(s) deducted from stock ";
        $user_remark = "[System Generated]invoice # <a href=order_viewfull.php?id=$bid>$invoice_no</a>";
        $insert = mysql_query("insert into os_stockrecord(pid,user_remarks,system_remarks,add_datetime,bid)values($pid,'$user_remark','$system_remark',now(),$bid)") or die(mysql_error());
    }
}

function restoreInventory($bid) {

    $get = mysql_query("select status,invoice_number from os_bill_details where id=$bid");

    if (mysql_result($get, 0, "status") >= 2) {
        $get_item = mysql_query("select * from os_bill_items where bid=$bid");
        $invoice_number = mysql_result($get, 0, "invoice_number");
        while ($a = mysql_fetch_array($get_item, MYSQL_ASSOC)) {
            $item_id = $a['item_id'];
            $amount = $a['quantity'];
            $pid = $a['pid'];
            updateInventory($item_id, $amount, "Add", "$invoice_number", $pid);
        }
    }
}

function updateVisitor() {

    $date = date("Y-m-d");

    $get = mysql_query("select * from os_totalvisit where visit_date='$date'");


    if (empty($_SESSION['visitorIP']) || mysql_num_rows($get) == 0) {
        $ip = $_SERVER['REMOTE_ADDR'];
        $_SESSION['visitorIP'] = $ip;

        if (mysql_num_rows($get) == 0) {
            mysql_query("insert into os_totalvisit(visit_date,total_visit) values('$date',1)") or die(mysql_error());
        } else {
            mysql_query("update os_totalvisit set total_visit=total_visit+1 where visit_date='$date'") or die(mysql_error());
        }
    }
}

?>
